// Copyright 2018 The QOS Authors

package main

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"gitee.com/jsonxt/rest_mail/handler"
	"github.com/gin-gonic/gin"
	"github.com/spf13/cobra"
)

var port int

func init() {
	rootCmd.PersistentFlags().IntVar(&port, "port", 8080, "监听端口")
}

var rootCmd = &cobra.Command{
	Use:   "rest_email",
	Short: "rest_email",
	Run: func(cmd *cobra.Command, args []string) {
		router := gin.Default()
		router.Use(func(c *gin.Context) {

			c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
			c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, GET, HEAD, OPTIONS, PUT, PATCH, DELETE")
			c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, QToken") //有使用自定义头 需要这个,Action, Module是例子

			if c.Request.Method != "OPTIONS" {
				c.Next()
			} else {
				c.AbortWithStatus(http.StatusOK)
			}
		})
		router.POST("/email", handler.EmailHander)
		//router.POST("/wechat", middleware.IPWhitelist(utils.NewLocalIPNet()), handler.WechatHander)
		router.POST("/wechat", handler.WechatHander)

		srv := &http.Server{
			Addr:    fmt.Sprintf("0.0.0.0:%d", port),
			Handler: router,
		}

		go func() {
			// service connections
			if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
				log.Fatalf("listen: %s\n", err)
			}
		}()

		// Wait for interrupt signal to gracefully shutdown the server with
		// a timeout of 5 seconds.
		quit := make(chan os.Signal)
		// kill (no param) default send syscanll.SIGTERM
		// kill -2 is syscall.SIGINT
		// kill -9 is syscall. SIGKILL but can"t be catch, so don't need add it
		signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
		<-quit
		log.Println("Shutdown Server ...")

		ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
		defer cancel()
		if err := srv.Shutdown(ctx); err != nil {
			log.Fatal("Server Shutdown:", err)
		}
		// catching ctx.Done(). timeout of 5 seconds.
		select {
		case <-ctx.Done():
			log.Println("timeout of 5 seconds.")
		}
		log.Println("Server exiting")
	},
}

func main() {
	if err := rootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}
